﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Tools;
using CSP.Common.Factories;
//using CSP.Common;

namespace CSP.Web.Common
{
    public partial class ImageValidation : System.Web.UI.Page
    {
        private const string _keyPrefix = "checkimg_";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["createimagekey"] != null)
            {
                string key = Request["createimagekey"].ToString();
                GetImageByKey(key);
            }
            else if (Request["checkimagekey"] != null)
            {
                string key = Request["checkimagekey"].ToString();
                string imgCode = Request["imgcode"].ToString();
                CheckImageByKey(key, imgCode);
            }
        }

        /// <summary>
        /// 此key一定要是全局唯一的
        /// </summary>
        /// <param name="key"></param>
        private void GetImageByKey(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return;
            }
            byte[] img = CSP.Common.Tools.CommonTool.CreateValidationImageByKey(key);

            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(img);
            Response.End();
        }

        /// <summary>
        /// 验证图片 0 验证码错误 1验证成功
        /// </summary>
        /// <param name="key"></param>
        private void CheckImageByKey(string key, string imgCode)
        {
            Response.ClearContent();
            Response.ContentType = "text/plain";

            if (string.IsNullOrWhiteSpace(key))
            {
                Response.Write("{\"status\":0,\"msg\":\"验证码错误!\"}");
            }

            bool checkValue = CommonTool.CheckImageByKeyAndImgCode(key, imgCode);
            if (!checkValue)
            {
                Response.Write("{\"status\":0,\"msg\":\"验证码错误!\"}");
            }
            else
            {
                Response.Write("{\"status\":1,\"msg\":\"验证成功!\"}");
            }
            Response.End();
        }
    }
}